import 'package:flutter/material.dart';
import 'package:flutter_demo/common/Git.dart';
import 'package:flutter_demo/common/UserModel.dart';
import 'package:flutter_demo/models/repo.dart';
import 'package:provider/provider.dart';
import 'package:flukit/flukit.dart';

import 'MyDrawer.dart';
import 'RepoItem.dart';

class HomeRoute extends StatefulWidget {
  @override
  _HomeRouteState createState() => _HomeRouteState();
}

class _HomeRouteState extends State<HomeRoute> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("首页"),
      ),
      body: _getHomeWiget(context),
      drawer: MyDrawer(),
    );
  }
}

// 获取首页数据
Widget _getHomeWiget(context) {
  UserModel userModel = Provider.of<UserModel>(context);
  // 当登陆信息中的用户不存在，则返回登陆按钮
  if (userModel.user == null) {
    return Center(
      child: RaisedButton(
          child: Text("登陆"),
          onPressed: () => Navigator.of(context).pushNamed("login")),
    );
  } else {
    // 下拉刷新的widget
    return InfiniteListView(
        onRetrieveData: (int page, List<Repo> items, bool refresh) async {
          var data = await Git(context).getRepos(
              refresh: refresh,
              queryParameters: {"page": page, "page_size": 20});
          items.addAll(data);
          // 返回是否到尾页
          // 如果page_size的条数不够20条，说明已经到尾页了
          return data.length == 20;
        },
        itemBuilder: (List<Repo> list, int index, BuildContext ctx) =>
            RepoItem(list[index]));
  }
}

